#include "form_language.h"
#include "ui_form_language.h"
#include <QDebug>
#include <QList>

Form_language::Form_language(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_language)
{
    ui->setupUi(this);
    model = new QStandardItemModel(this);
    InitUI();
    setLanguageItem();
}

Form_language::~Form_language()
{
    delete ui;
}

void Form_language::InitUI()
{
    ui->bt_chose->setText(tr("chose language"));
    ui->lb_language_prompt->setText(tr("Please choose a language you are familiar with"));
    setWindowFlags(windowFlags()&~Qt::WindowMinimizeButtonHint);
    ui->listView->setModelColumn(3);
    set_default();
}

void Form_language::setLanguageItem()
{
    Sport_language sl;
    QMap<QString, QString>::iterator it;
    QString seted_language = Config_file().get("sys", "language").toString();
    int language_index = 0;
    bool find_index = false;
    for (it = sl.language_mps.begin(); it != sl.language_mps.end(); ++it){
        QString add_lang_key = it.key();
        QString add_lang = it.value();
        QStandardItem* col1 = new QStandardItem(add_lang);
        QStandardItem* col2 = new QStandardItem(add_lang_key);
        QList<QStandardItem*> one_row;
        one_row.append(col1);
        one_row.append(col2);
        model->appendRow(one_row);
        if(!seted_language.compare(add_lang_key)){
            find_index = true;
        }
        else if (!seted_language.length() && !add_lang_key.compare("EN")){
            find_index = true;
        }
        if(!find_index){
            language_index += 1;
        }
    }
    ui->listView->setModel(model);
    ui->listView->setCurrentIndex(ui->listView->model()->index(language_index, 0));
    qInfo()<< "find index "<< language_index;
}

void Form_language::showEvent(QShowEvent *)
{
}

void Form_language::set_default(QString lang)
{
}


void Form_language::on_bt_chose_clicked()
{
    int index = ui->listView->currentIndex().row();
    QMap<QString, QString>::iterator it;
    Sport_language sl;
    QString language_key;
    int current_index = 0;
    for (it = sl.language_mps.begin(); it != sl.language_mps.end(); ++it){
        if (index == current_index){
            language_key = it.key();
        }
        current_index += 1;
    }
    Config_file().set("sys", "language", QVariant(language_key.toStdString().c_str()));
    setStatusTip(tr("language set success"));

    qInfo() << "current language:" << language_key.toStdString().c_str();
}

Sport_language::Sport_language()
{
    language_mps.insert("UI_ZH", "English");
    language_mps.insert("UI_EN", "简体中文");
}
